package com.journey.org.ui.knowledge.gankio.detail

import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.os.StrictMode
import android.text.Html
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.viewModelScope
import com.journey.org.BR
import com.journey.org.R
import com.journey.org.databinding.FragmentGankDetailBinding
import com.mvvmhabit.org.base.BaseFragment
import com.zzhoujay.markdown.MarkDown
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.IOException
import java.net.URL

/**
 * @Date: 2020/12/17 15:57
 * @Author:小妖
 * @Description: 干货文章详情
 */
class GankDetailFragment : BaseFragment<FragmentGankDetailBinding, GankDetailViewModel>() {

    private lateinit var id: String
    override fun initParam() {
        super.initParam()
        id = arguments?.getString("id")!!
    }

    override fun initVariableId(): Int = BR.viewModel
    override fun initViewModel(): Class<GankDetailViewModel> = GankDetailViewModel::class.java
    override fun initContentView(
        inflater: LayoutInflater?,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): Int = R.layout.fragment_gank_detail

    override fun initData() {
        super.initData()
        if (id.isNotEmpty()) {
            mViewModel?.loadGankArticleDetail(id)
        }
        mViewModel?.onGankDetailContentEvent?.observe(this, Observer { content ->
            mBinding.tvBody.post {
                val spanned = MarkDown.fromMarkdown(content, {
                    var drawable: Drawable?
                    try {
                        drawable = drawableFromUrl(it)
                        drawable?.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
                    } catch (e: IOException) {
                        drawable = ColorDrawable(Color.LTGRAY)
                        drawable.setBounds(
                            0,
                            0,
                            mBinding.tvBody.width - mBinding.tvBody.paddingLeft - mBinding.tvBody.paddingRight,
                            400
                        )
                    }
                    return@fromMarkdown drawable
                }, mBinding.tvBody)
                mBinding.tvBody.text = spanned
            }
        })
    }

   private fun drawableFromUrl(url: String): Drawable? {
        val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
        StrictMode.setThreadPolicy(policy)
        val connection = URL(url).openConnection()
        connection.connect()
        val input = connection.getInputStream()
        return BitmapDrawable(BitmapFactory.decodeStream(input))
    }

}